package com.zcy.day1.homeWork.stack;

/**
 * 手撸一个栈
 * @param <T>
 */
public class StackDemo<T> {
    /**
     * 栈长度
     */
    private Integer length;

    /**
     * 栈大小
     */
    private Integer size = 0;

    /**
     * 栈内元素
     */
    private T[] ts;

    public StackDemo() {
        this.length = 5;
        this.ts = (T[]) new Object[length];
    }

    public StackDemo(int length) {
        this.length = length;
        this.ts = (T[]) new Object[length];
    }

    public T peek(){
        return ts[size-1];
    }

    public T pop(){
        T t = ts[size-1];
        ts[size-1] = null;
        size--;
        return t;

    }

    public boolean push(T t){
        if (this.size >= this.length){
            int oldLength = this.length;
            this.length = oldLength + (oldLength >> 1);
            T[] newTs = (T[]) new Object[this.length];
            System.arraycopy(ts,0,newTs,0,length);
            ts = newTs;
        }
        ts[size] = t;
        size++;
        return true;
    }
}
